<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Finance;

use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;

/**
 * 付款类
 *
 * @author Angl
 */
class Payment
{
    private $pay_id = null;
    private $model = null;

    /**
     * Payment 构造.
     *
     * @param int $pay_id
     */
    public function __construct($pay_id)
    {
        $this->pay_id = intval($pay_id);
        $this->model = M("pay_log");
    }

    /**
     * 新增付款记录
     *
     * @param int $car_id       车辆id
     * @param int $order_id        拍单id
     * @param     $type         1首款,2尾款
     * @param     $fid          关联打款帐号信息ID
     * @param     $bank_account 打款账号信息
     * @param     $create_time
     *
     * @return bool|mixed
     */
    public static function create($car_id, $order_id, $type, $fid = 0, $bank_account = '')
    {
        if ($car_id < 1 || $order_id < 1 || $type < 1) return false;
        return M("pay_log")->add([
            'car_id' => $car_id,
            'order_id' => $order_id,
            'pay_type' => $type,
            'fid' => $fid,
            'bank_account' => $bank_account,
            'createtime' => date("Y-m-d H:i:s")
        ]);
    }

    /**
     * 更新付款信息
     *
     * @param $data
     *
     * @return bool
     */
    public function update($data)
    {
        if ($this->pay_id)
            unset($data['pay_id']);
        $map = [
            'pay_id' => $this->pay_id,
        ];
        return M("pay_log")->where($map)->save($data);
    }

    /**
     * 获取付款信息
     *
     * @return array mixed
     */
    public function info()
    {
        $map = ['pay_id' => $this->pay_id];
        return $this->model->where($map)->find();
    }

    /**
     * 计算车主付款金额
     * 拍卖最高价 + 公司补贴 + 分享抬价 - 协商车主降价 - 检测费
     *
     * @param $order_id
     *
     * @return mixed
     */
    public static function owner_final_price($order_id)
    {
        $fields = "o.bid_best_price,bidding_best_price,o.company_subsidies,o.depreciate,
                   c.bid_up_price,c.car_source";
        $info = M("order")->alias("o")->field($fields)
            ->join(C("DB_PREFIX") . "cars AS c ON c.car_id=o.car_id")
            ->where("order_id=" . $order_id)->find();
        $highest_price = $info['bid_best_price'] > $info['bidding_best_price'] ? $info['bid_best_price'] : $info['bidding_best_price'];
        //4s店车源添加检测费
//        if($info['car_source'] == 1) {
//            $owner_pay_price = $highest_price + $info['company_subsidies'] + $info['bid_up_price'] - $info['depreciate'] - $info['check_fee'];
//        }else {
        $owner_pay_price = $highest_price + $info['company_subsidies'] + $info['bid_up_price'] - $info['depreciate'];
//        }
        return $owner_pay_price;
    }

    /**
     * 获取付款凭证
     *
     * @param $order_id
     *
     * @return bool|mixed
     */
    public static function get_payment_img($order_id)
    {
        if ($order_id < 1) return false;
        return M("payment_voucher")->where("order_id=" . $order_id)->select();
    }

    /**
     * 获取单条付款记录
     *
     * @param int $type 1首款;2尾款
     *
     * @return mixed
     */
    public function get_info_by_type($type)
    {
        $map = ['order_id' => $this->order_id];
        $map['pay_type'] = $type;
        return $this->model->where($map)->find();
    }

    /**
     * 获取已付车款金额
     *
     * @param  int $car_id
     *
     * @return array amount
     */
    public function get_car_paid($car_id)
    {
        if ($car_id < 1) return false;
        $map['car_id'] = ['eq', $car_id];
        return $this->model->where($map)->sum('amount');
    }


    public static function get_list($page, $limit, $params = array())
    {
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $order = "pl.createtime desc";
        $map = [];
        $status = intval($params['t']);
        if ($status == 0) {
            // $map['o.status'] = 8;
            $map['pl.pay_type'] = 1;
            $map['pl.status'] = 0;
        } elseif ($status == 1) {
            $map['o.status'] = array('in', array(11, 12));
            $map['pl.pay_type'] = 2;
            $map['pl.status'] = 0;
        } elseif ($status == 2) {
            if (empty($params['pay_type'])) {
                $map['pl.pay_type'] = [['eq', 1], ['eq', 2], 'or'];
            } else {
                $map['pl.pay_type'] = $params['pay_type'];
            }
            $map['pl.status'] = 1;
            $order = "pl.last_update desc";
        } elseif ($status == 3) {
            $map['pl.status'] = 2;
        }
        //车辆来源
        if (!empty($params['car_source'])) {
            $map['c.car_source'] = $params['car_source'];
        }
        //车辆所在地
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['in', $params['location_area']];
        }
        //拍单号
        if (!empty($params['order_no'])) {
            $map['o.order_no'] = $params['order_no'];
        }
        //车主姓名
        if (!empty($params['seller_name'])) {
            $map['co.seller_name'] = ['like', '%' . $params['seller_name'] . '%'];
        }
        //车主电话
        if (!empty($params['seller_phone'])) {
            $map['co.phone'] = $params['seller_phone'];
        }

        //付款时间
        if (!empty($params['start_time']) || !empty($params['end_time'])) {
            if (empty($params['start_time'])) {
                $map['pl.last_update'] = array("elt", $params['end_time'] . " 23:59:59");
            } elseif (empty($params['end_time'])) {
                $map['pl.last_update'] = array("gt", $params['start_time'] . " 00:00:00");
            } else {
                $map['pl.last_update'] = array(array("gt", $params['start_time'] . " 00:00:00"), array("elt", $params['end_time'] . " 23:59:59"));
            }
        }

        if (!empty($params['keyword'])) {
            $keyword = "%{$params['keyword']}%";
            $where['c.car_no'] = array('like', $keyword);
            $where['o.order_no'] = array('like', $keyword);
            $where['co.seller_name'] = array('like', $keyword);
            $where['co.phone'] = array('like', $keyword);
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $cols = "pl.pay_id,o.order_id,o.order_no,o.first_money,o.tail_money,o.dealer_pay_status
                ,c.car_no,c.location_area,c.car_id,c.brand_id,c.series_id,pl.pay_type,c.model_id
                ,c.car_source,c.three_in_one,c.is_dealer_breach
                ,co.seller_name,co.phone,pl.amount,pl.createtime,pl.last_update";
        $prefix = C("DB_PREFIX");
        $total = M('pay_log')->alias("pl")
            ->join($prefix . "order as o ON o.order_id=pl.order_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_owner as co ON c.owner_id=co.owner_id")
            ->where($map)->count();

        $list = M('pay_log')->alias("pl")->field($cols)
            ->join($prefix . "order as o ON o.order_id=pl.order_id")
            ->join($prefix . "cars as c ON c.car_id=o.car_id")
            ->join($prefix . "car_owner as co ON c.owner_id=co.owner_id")
            ->where($map)->page($page)->limit($limit)->order($order)->select();
//         echo M()->getLastSql();
        if (!empty($list)) {
            $cm = new CarModel();
            $addr = new Address();
            foreach ($list as $key => $vl) {
                //车型
                $brand = $cm->get_model_by_id($vl['brand_id'], 'brand');
                $series = $cm->get_model_by_id($vl['series_id'], 'series');
                $model = $cm->get_model_by_id($vl['model_id']);
                $list[$key]['car_model'] = $brand['name'] . $series['name'] . $model['name'];
                //所在地
                if ($vl['location_area']) {
                    $location_area = $addr->get_name_by_code($vl['location_area']);
                    $list[$key]['location_area_str'] = $location_area;
                } else {
                    $list[$key]['location_area'] = '无';
                }
                //付款凭证
                if ($vl['car_source'] == 1) {
                    $prof = static::get_payment_img($vl['order_id']);
                    if (empty($prof)) {
                        $list[$key]['prof'] = "无";
                    } else {
                        $list[$key]['prof'] = "有";
                    }
                } else {
                    $list[$key]['prof'] = "--";
                }
            }
        }
        $data = ['total' => $total, 'list' => $list];
        return $data;
    }

    public static function getInfoByMap($map)
    {
        return M('pay_log')->where($map)->find();
    }

    /**
     * 获取车主确认后4s店付款账号信息
     */
    public static function get_fours_pay_bank_account($map)
    {
        return M('pay_log')->where($map)->getField('bank_account');
    }


	/**
	 *  根据条件，获取付款信息
	 *
	 * @param $map 条件
	 * @return mixed
	 */
	public static function getPayInfoByCondition($map){
	    return M('pay_log')->where($map)->find();
    }
}

//end class
